package imaa.escola.disciplina.repository;

import imaa.escola.disciplina.datatransfer.DisciplinaDto;
import imaa.escola.disciplina.datatransfer.PesquisaDisciplinaDto;
import imaa.escola.disciplina.domain.Disciplina;
import imaa.escola.instrumento.datatransfer.InstrumentoDto;
import imaa.escola.instrumento.repository.InstrumentoRepository;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

public class DisciplinaRepositoryImpl implements DisciplinaRepositoryCustom {

	@Autowired
	private DisciplinaRepository disciplinaRepository;
	
	@Autowired
	private InstrumentoRepository instrumentoRepository;

	@Autowired
	private JdbcTemplate template;

	@SuppressWarnings("rawtypes")
	public List<DisciplinaDto> findByExample(PesquisaDisciplinaDto dto) {
		String sql = "SELECT * FROM disciplina WHERE 1=1 ";
		if (dto.descricao != null)
			sql += "AND LOWER(descricao) LIKE LOWER('%" + dto.descricao
					+ "%') ";
		if (dto.idInstrumento != null)
			sql += "AND SEQ_INSTRUMENTO = " + dto.idInstrumento + " ";

		List<DisciplinaDto> lista = new ArrayList<DisciplinaDto>();
		List<Map<String, Object>> rows = template.queryForList(sql);

		for (Map row : rows) {
			DisciplinaDto disciplina = new DisciplinaDto();
			disciplina.id =(Long.parseLong(String.valueOf(row.get("SEQ_DISCIPLINA"))));
			disciplina.descricao = ((String) (row.get("DSC_DISCIPLINA")));
			Long idInstrumento = Long.parseLong(String.valueOf(row.get("SEQ_INSTRUMENTO")));
			disciplina.instrumento = (new InstrumentoDto(instrumentoRepository.findOne(idInstrumento)));

			lista.add(disciplina);
		}
		return lista;
	}


	
	}


